import { defineStore } from 'pinia'
import { ref, computed, readonly } from 'vue'
import * as todosApi from '@/api/todos'
import type { TodoList, Todo, CreateTodoRequest, UpdateTodoRequest } from '@/types/todo'

export const useTodosStore = defineStore('todos', () => {
  // 状态
  const todoLists = ref<TodoList[]>([])
  const todos = ref<Todo[]>([])
  const currentListId = ref<number | null>(null)
  const isLoading = ref(false)

  // 计算属性
  const currentList = computed(() => {
    return todoLists.value.find(list => list.id === currentListId.value) || null
  })

  const currentTodos = computed(() => {
    if (!currentListId.value) return todos.value
    return todos.value.filter(todo => todo.listId === currentListId.value)
  })

  const completedTodos = computed(() => {
    return currentTodos.value.filter(todo => todo.completed)
  })

  const pendingTodos = computed(() => {
    return currentTodos.value.filter(todo => !todo.completed)
  })

  const todayTodos = computed(() => {
    const today = new Date().toISOString().split('T')[0]
    return todos.value.filter(todo => 
      todo.dueDate && todo.dueDate.toISOString().split('T')[0] === today
    )
  })

  const overdueTodos = computed(() => {
    const today = new Date().toISOString().split('T')[0]
    return todos.value.filter(todo => 
      todo.dueDate && 
      todo.dueDate.toISOString().split('T')[0] < today && 
      !todo.completed
    )
  })

  const upcomingTodos = computed(() => {
    const today = new Date()
    const nextWeek = new Date(today.getTime() + 7 * 24 * 60 * 60 * 1000)
    const todayStr = today.toISOString().split('T')[0]
    const nextWeekStr = nextWeek.toISOString().split('T')[0]
    
    return todos.value.filter(todo => 
      todo.dueDate && 
      todo.dueDate.toISOString().split('T')[0] > todayStr && 
      todo.dueDate.toISOString().split('T')[0] <= nextWeekStr &&
      !todo.completed
    )
  })

  // 获取待办事项列表
  const fetchTodoLists = async () => {
    try {
      isLoading.value = true
      const response = await todosApi.getTodoLists()
      
      if (response.success && response.data) {
        todoLists.value = response.data.todoLists
      }
    } catch (error) {
      console.error('Failed to fetch todo lists:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  // 创建待办事项列表
  const createTodoList = async (name: string) => {
    try {
      isLoading.value = true
      const response = await todosApi.createTodoList(name)
      
      if (response.success && response.data) {
        todoLists.value.push(response.data.todoList)
        return response.data.todoList
      }
    } catch (error) {
      console.error('Failed to create todo list:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  // 更新待办事项列表
  const updateTodoList = async (id: number, name: string) => {
    try {
      isLoading.value = true
      const response = await todosApi.updateTodoList(id, name)
      
      if (response.success && response.data) {
        const index = todoLists.value.findIndex(list => list.id === id)
        if (index !== -1) {
          todoLists.value[index] = response.data.todoList
        }
        return response.data.todoList
      }
    } catch (error) {
      console.error('Failed to update todo list:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  // 删除待办事项列表
  const deleteTodoList = async (id: number) => {
    try {
      isLoading.value = true
      await todosApi.deleteTodoList(id)
      
      todoLists.value = todoLists.value.filter(list => list.id !== id)
      todos.value = todos.value.filter(todo => todo.listId !== id)
      
      // 如果删除的是当前选中的列表，切换到第一个列表
      if (currentListId.value === id) {
        currentListId.value = todoLists.value.length > 0 ? todoLists.value[0].id : null
      }
    } catch (error) {
      console.error('Failed to delete todo list:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  // 获取待办事项
  const fetchTodos = async (params?: {
    listId?: number
    completed?: boolean
    priority?: number
    limit?: number
  }) => {
    try {
      isLoading.value = true
      const response = await todosApi.getTodos(params)
      
      if (response.success && response.data) {
        console.log('API Response:', response.data)
        console.log('Todos data:', response.data.todos)
        todos.value = response.data.todos
      }
    } catch (error) {
      console.error('Failed to fetch todos:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  // 创建待办事项
  const createTodo = async (data: CreateTodoRequest) => {
    try {
      isLoading.value = true
      const response = await todosApi.createTodo(data)
      
      if (response.success && response.data) {
        // @ts-ignore
        todos.value.unshift(response.data.todo)
        return response.data.todo
      }
    } catch (error) {
      console.error('Failed to create todo:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  // 更新待办事项
  const updateTodo = async (id: number, data: UpdateTodoRequest) => {
    try {
      isLoading.value = true
      const response = await todosApi.updateTodo(id, data)
      
      if (response.success && response.data) {
        const index = todos.value.findIndex(todo => todo.id === id)
        if (index !== -1) {
          // @ts-ignore
          todos.value[index] = response.data.todo
        }
        return response.data.todo
      }
    } catch (error) {
      console.error('Failed to update todo:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  // 切换待办事项完成状态
  const toggleTodo = async (id: number) => {
    const todo = todos.value.find(t => t.id === id)
    if (!todo) return
    
    try {
      const response = await todosApi.toggleTodo(id, !todo.completed)
      
      if (response.success && response.data) {
        const index = todos.value.findIndex(t => t.id === id)
        if (index !== -1) {
          // @ts-ignore
          todos.value[index] = response.data.todo
        }
        return response.data.todo
      }
    } catch (error) {
      console.error('Failed to toggle todo:', error)
      throw error
    }
  }

  // 删除待办事项
  const deleteTodo = async (id: number) => {
    try {
      isLoading.value = true
      await todosApi.deleteTodo(id)
      
      todos.value = todos.value.filter(todo => todo.id !== id)
    } catch (error) {
      console.error('Failed to delete todo:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  // 设置当前列表
  const setCurrentList = (listId: number | null) => {
    currentListId.value = listId
  }

  // 获取指定列表的待办事项
  const fetchTodosByList = async (listId: number) => {
    try {
      isLoading.value = true
      const response = await todosApi.getTodosByList(listId)
      
      if (response.success && response.data) {
        // 更新对应列表的待办事项
        todos.value = todos.value.filter(todo => todo.listId !== listId)
        // @ts-ignore
        todos.value.push(...response.data.todos)
      }
    } catch (error) {
      console.error('Failed to fetch todos by list:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  return {
    // 状态
    todoLists: readonly(todoLists),
    todos: readonly(todos),
    currentListId: readonly(currentListId),
    isLoading: readonly(isLoading),
    
    // 计算属性
    currentList,
    currentTodos,
    completedTodos,
    pendingTodos,
    todayTodos,
    overdueTodos,
    upcomingTodos,
    
    // 方法
    fetchTodoLists,
    createTodoList,
    updateTodoList,
    deleteTodoList,
    fetchTodos,
    fetchTodosByList,
    createTodo,
    updateTodo,
    toggleTodo,
    deleteTodo,
    setCurrentList
  }
})